package com.cfets.annualAssessment.backgroundController;
import com.alibaba.fastjson.JSONArray;
import com.cfets.annualAssessment.entity.*;
import com.cfets.annualAssessment.mapper.CfetsNewsMapper;
import com.cfets.annualAssessment.mapper.CfetsPicsMapper;
import com.cfets.annualAssessment.service.*;
import com.cfets.annualAssessment.util.CheckUtil;
import com.cfets.annualAssessment.util.RedisRunner;
import com.sun.net.httpserver.Authenticator;
import jdk.nashorn.internal.ir.RuntimeNode;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.log4j.Log4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by ShenYiChou on 2017/9/5.
 */
@Log4j
@Controller
@RequestMapping("/admin/GameScore")
public class GameScore {
    @Autowired
    private RedisRunner redisRunner;
    @Autowired
    private CfetsNewsService cfetsNewsService;

    @Autowired
    private GameScoreService gameScoreService;

    @Autowired
    private CfetsCookieService cfetsCookieService;

    @Autowired
    private CfetsPicsServie cfetsPicsServie;

    @Autowired
    private CfetsPptService cfetsPptService;


    @Autowired
    private  CfetsPlanetService cfetsPlanetService;

    @RequestMapping("/index")
    public String index(Model model){
        return "meet";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> meetList(GameSe gameSe){
        List<GameSe> meetList = gameScoreService.getGamePage(gameSe);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(meetList);
        tableContainer.setiTotalDisplayRecords(gameSe.getTotalCount());
        tableContainer.setiTotalRecords(gameSe.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }
//    @RequestMapping(value = "/restful/GetSit",method = RequestMethod.POST)
//    public ResponseEntity<?> meetList(Gamesit gamesit){
//        List<Gamesit> meetList = gameScoreService.getSit(gamesit);
//        return new ResponseEntity<>(meetList, HttpStatus.OK);
//    }
    @RequestMapping(value = "/restful",method = RequestMethod.GET)
    public ResponseEntity<?> getMeetByToken(String token){
        if (StringUtils.isEmpty(token)){
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        GameSe gameSe = this.gameScoreService.getGameByToken(token);
        return new ResponseEntity<>(gameSe, HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/login",method = RequestMethod.POST)
    public ResponseEntity<?> meetLogin(GameSe gameSe){
        String token = UUID.randomUUID().toString();
        GameSe gameSeSave = new GameSe();
        Gamesit gamesit = new Gamesit();
        if(CheckUtil.isEmpty(gameSe.getTel())){
            List<GameSe> vipList = gameScoreService.getVIPLogin(gameSe);
            if(vipList.isEmpty()||vipList.size()>1){
                return new ResponseEntity<>(false, HttpStatus.OK);
            }else {
                gameSeSave = vipList.get(0);
//                redisRunner.cacheAddUpdate(Constant.REDIS_FRONT_END_PERMISSION_DB,
//                        token, gameSeSave, -1);
            }
        }else{
            List<GameSe> meetList = gameScoreService.getLogin(gameSe);
            if(meetList.isEmpty()||meetList.size()>1){
                return new ResponseEntity<>(false, HttpStatus.OK);
            }else {
                gameSeSave = meetList.get(0);
//                redisRunner.cacheAddUpdate(Constant.REDIS_FRONT_END_PERMISSION_DB,
//                        token, gameSeSave, -1);
            }
        }
        gamesit.setOrg_name(token);
        gamesit.setSit_x(gameSeSave.getId());
        if (!this.gameScoreService.HaveSign(gameSeSave)||!this.gameScoreService.newGameSit(gamesit))
        { return new ResponseEntity<>(false, HttpStatus.OK);}
        return new ResponseEntity<>(token, HttpStatus.OK);
    }



    @RequestMapping(value = "/restful/message", method = RequestMethod.POST)

    public ResponseEntity<?> getMessage(CfetsNews news){
        List<CfetsNews> cfetsNewsList  = this.cfetsNewsService.getNews(news);
        return  new ResponseEntity<>(cfetsNewsList,HttpStatus.OK);
}


    // 交易星球登录

   @RequestMapping(value = "/restful/planetLogin",method = RequestMethod.POST)
   public ResponseEntity<?> getPlanetLogin(CfetsPlanet cfetsPlanet){
       String token = UUID.randomUUID().toString();
       PlanetToken planetToken = new PlanetToken();
       CfetsPlanet cfetsPlanet1 = new CfetsPlanet();

        List<CfetsPlanet> cfetsPlanetList = this.cfetsPlanetService.getPlantLogin(cfetsPlanet);
        if (cfetsPlanetList.isEmpty()){
            return new ResponseEntity<>(false,HttpStatus.OK);
        }else {
            cfetsPlanet1 = cfetsPlanetList.get(0);
        }

        planetToken.setTokenid(token);
        planetToken.setUserid(cfetsPlanet1.getId());
       // planetToken.setUsername(cfetsPlanet1.getName());
        if (!this.cfetsPlanetService.HaveSign(cfetsPlanet1)|| !this.cfetsPlanetService.newPlanetToken(planetToken)){
            return  new ResponseEntity<>(false,HttpStatus.OK);
        }

       return  new ResponseEntity<>(token,HttpStatus.OK);
   }



   // 根据交易星球的token去获取交易员信息
    @RequestMapping(value = "/restful/planetMessages",method = RequestMethod.POST)
    public  ResponseEntity<?>getplanetMessages(String token){

        if (StringUtils.isEmpty(token)){
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
         CfetsPlanet cfetsPlanet = cfetsPlanetService.getPlanetMessagesByToken(token);
        return  new ResponseEntity<>(cfetsPlanet,HttpStatus.OK);


    }
@RequestMapping(value = "/restful/pics",method = RequestMethod.GET)
    public  ResponseEntity<?>getPics(CfetsPics cfetsPics){ // 获取标识
    List<CfetsPics> cfetsPicsList = this.cfetsPicsServie.getList(cfetsPics);

    return  new ResponseEntity<>(cfetsPicsList,HttpStatus.OK);
}

@RequestMapping(value = "restful/ppts",method = RequestMethod.GET)
     public  ResponseEntity<?>getPPT(CfetsPpt cfetsPpt){
        List<CfetsPpt> cfetsPptList = this.cfetsPptService.getList(cfetsPpt);

        return  new ResponseEntity<>(cfetsPptList,HttpStatus.OK);
}


 @RequestMapping(value = "/restful/status",method = RequestMethod.POST)
    public ResponseEntity<?> getNumber( @RequestParam(value = "id" ) int idNum,@RequestParam(value = "touch") int isTouch){
        // totalCount 作为点赞的累计数，根据id找到对应的点赞数，然后根据0来针对totalCount+1
     Map<String, Integer> m = new HashMap<String, Integer>();
     int totalCount=0;
     CfetsNews cfetsNews = new CfetsNews();
     totalCount = this.cfetsNewsService.getCfetsNewsbyId(idNum).getNum();
     if (isTouch==0){ // 默认传 0 ，可以点赞数+1
         totalCount++; // 点赞数+1
     }

         // 将点赞数更新到数据表中
         cfetsNews = this.cfetsNewsService.getCfetsNewsbyId(idNum);
         cfetsNews.setNum(totalCount);
         this.cfetsNewsService.updateCfetsNews(cfetsNews);
         m.put("id", idNum);
         m.put("num", totalCount);

         return new ResponseEntity<>(m, HttpStatus.OK);

 }

    @RequestMapping(value = "/import")
    public ResponseEntity<?> importExcel(MultipartFile meetFile) {
        try {
            this.gameScoreService.deleteAllGameSe();
            this.gameScoreService.deleteAllGameSit();
            XSSFWorkbook xwb = new XSSFWorkbook(meetFile.getInputStream());
            XSSFSheet sheet = xwb.getSheetAt(0);
            XSSFRow row;
            GameSe gameSe = new GameSe();
            for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
                if (i == 0) {
                    continue;
                }
                gameSe.setId(null);
                row = sheet.getRow(i);
                if(Objects.equals(row.getCell(1).toString(), "")){
                    return new ResponseEntity<>(-1, HttpStatus.OK);//新增失败为空 -1
                }
                gameSe.setName(row.getCell(1)!=null?row.getCell(1).toString():"");
                gameSe.setTel(row.getCell(2)!=null?row.getCell(2).toString():"");
                gameSe.setOrg_name(row.getCell(3)!=null?row.getCell(3).toString():"");
                gameSe.setTag(row.getCell(4)!=null?row.getCell(4).toString():"");
                gameSe.setSit_x(row.getCell(5)!=null?row.getCell(5).toString():"");
                gameSe.setSit_y(row.getCell(6)!=null?row.getCell(6).toString():"");
                boolean flag = this.gameScoreService.newGameSe(gameSe);
                if (!flag) {
                    return new ResponseEntity<>(false, HttpStatus.OK);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }
    @RequestMapping(value = "/restful/update")
    public ResponseEntity<?> updateExcel(MultipartFile meetFile) {
        try {
            XSSFWorkbook xwb = new XSSFWorkbook(meetFile.getInputStream());
            XSSFSheet sheet = xwb.getSheetAt(0);
            XSSFRow row;
            GameSe gameSe = new GameSe();
            for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
                if (i == 0) {
                    continue;
                }
                gameSe.setId(null);
                row = sheet.getRow(i);
                if(Objects.equals(row.getCell(1).toString(), "")){
                    return new ResponseEntity<>(false, HttpStatus.OK);
                }
                if(row.getCell(2)==null||CheckUtil.isEmpty(row.getCell(2).toString())) {
                    GameSe tmp = new GameSe();
                    tmp.setName(row.getCell(1) != null ? row.getCell(1).toString() : "");
                    tmp.setTag(row.getCell(4)!=null?row.getCell(4).toString():"");
                    List<GameSe> vipList = gameScoreService.getVIPLogin(tmp);
                    if(vipList.size()==1){
                        gameSe = vipList.get(0);
                    }
                }else{
                    GameSe tmp = new GameSe();
                    tmp.setName(row.getCell(1) != null ? row.getCell(1).toString() : "");
                    tmp.setTel(row.getCell(2)!=null?row.getCell(2).toString():"");
                    List<GameSe> meetList = gameScoreService.getLogin(tmp);
                    if(meetList.size()==1){
                        gameSe = meetList.get(0);
                    }
                }

                gameSe.setName(row.getCell(1) != null ? row.getCell(1).toString() : "");
                gameSe.setTag(row.getCell(4)!=null?row.getCell(4).toString():"");
                gameSe.setTel(row.getCell(2)!=null?row.getCell(2).toString():"");
                gameSe.setOrg_name(row.getCell(3)!=null?row.getCell(3).toString():"");
                gameSe.setSit_x(row.getCell(5)!=null?row.getCell(5).toString():"");
                gameSe.setSit_y(row.getCell(6)!=null?row.getCell(6).toString():"");
                boolean flag;
                if(CheckUtil.isEmpty(gameSe.getId())){
                    flag = this.gameScoreService.newGameSe(gameSe);
                }else{
                    flag = this.gameScoreService.updateGameSe(gameSe);
                }
                if (!flag) {
                    return new ResponseEntity<>(false, HttpStatus.OK);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.OK);
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }
}
